package cn.star.jots.user.service.impl;

import cn.star.jots.base.exception.ServiceException;
import cn.star.jots.base.response.StatusCode;
import cn.star.jots.employee.pojo.vo.EmployeeVO;
import cn.star.jots.user.mapper.UserMapper;
import cn.star.jots.user.pojo.dto.*;
import cn.star.jots.user.pojo.entity.User;
import cn.star.jots.user.pojo.vo.UserVO;
import cn.star.jots.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public List<UserVO> selectAll(UserQuery userQuery) {
        log.debug("查询用户,参数:{}", userQuery);
        return userMapper.selectAll(userQuery);
    }

    @Override
    public void saveInfo(UserSaveParam userSaveParam) {
        log.debug("保存用户,参数:{}", userSaveParam);
        User user = new User();
        BeanUtils.copyProperties(userSaveParam, user);
        if (user.getId() == null) {
            if (isPhoneExist(userSaveParam.getPhone())) {
                log.warn("手机号已存在:{}", userSaveParam.getPhone());
                throw new ServiceException(StatusCode.PHONE_EXIST);
            }
            user.setId(generateUUIDString());
            user.setUsername(generateUsername());
            user.setNickname(generateUsername());
            user.setPassword("123456");
            user.setAvatar("/base/base.jpg");
            user.setCreateTime(new Date());
            userMapper.save(user);
        } else {
            user.setUpdateTime(new Date());
            userMapper.update(user);
        }
    }

    @Override
    public void delete(String id) {
        log.debug("删除用户,参数:{}", id);
        userMapper.delete(id);
    }

    @Override
    public void deleteBatch(List<String> ids) {
        log.debug("批量删除用户,参数:{}", ids);
        for (String id : ids){
            userMapper.delete(id);
        }
    }

    @Override
    public void register(UserSaveParam userSaveParam) {
        log.debug("注册用户,参数:{}", userSaveParam);
        User user = new User();
        BeanUtils.copyProperties(userSaveParam, user);
        if (isPhoneExist(userSaveParam.getPhone())) {
            throw new ServiceException(StatusCode.PHONE_EXIST);
        }
        if (isEmailExist(userSaveParam.getEmail())) {
            throw new ServiceException(StatusCode.EMAIL_EXIST);
        }
        user.setId(generateUUIDString());
        user.setUsername(generateUsername());
        user.setAvatar("/base/base.jpg");
        user.setCreateTime(new Date());
        userMapper.save(user);
    }

    @Override
    public void updateInfo(UserUpdateParam userUpdateParam) {
        log.debug("修改用户信息,参数:{}", userUpdateParam);
        User user = new User();
        BeanUtils.copyProperties(userUpdateParam, user);
        user.setUpdateTime(new Date());
        userMapper.update(user);
    }

    @Override
    public void savePassword(UserSavePassword userSavePassword) {
        log.debug("修改密码:userSavePassword={}", userSavePassword);
        UserVO userVO = userMapper.selectById(userSavePassword.getId());
        if (userVO.getPassword().equals(userSavePassword.getOldPassword())) {
            if (userVO.getPassword().equals(userSavePassword.getPassword())){
                throw new ServiceException(StatusCode.NEW_OLD_PASSWORD_ERROR);
            } else {
                User user = new User();
                user.setId(userSavePassword.getId());
                user.setPassword(userSavePassword.getPassword());
                user.setUpdateTime(new Date());
                userMapper.update(user);
            }
        } else {
            log.warn("旧密码错误:{}", userSavePassword.getOldPassword());
            throw new ServiceException(StatusCode.OLD_PASSWORD_ERROR);
        }
    }

    private boolean isEmailExist(String email) {
        UserVO userVO = userMapper.selectByEmail(email);
        return userVO != null;
    }

    private boolean isPhoneExist(String phone) {
        UserVO userVO = userMapper.selectByPhone(phone);
        return userVO != null;
    }
    private String generateUUIDString() {
        String uuid;
        do {
            uuid = UUID.randomUUID().toString().replaceAll("-", "");
        } while (isUuidExists(uuid));
        return uuid;
    }

    private boolean isUuidExists(String uuid) {
        // 假设有一个方法可以检查给定的UUID是否存在于数据库中
        // 你需要在你的UserMapper中实现这样的查询
        return userMapper.existsById(uuid) > 0;
    }

    private String generateUsername() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String currentDateStr = LocalDate.now().format(formatter);

        // 初始化四位数字部分，从0000开始
        int numberPart = 0;

        String username;
        do {
            // 将数字部分格式化为四位数，不足的前面补零
            String formattedNumber = String.format("%04d", numberPart);
            username = "jots_" + currentDateStr + formattedNumber;

            // 检查是否有重复的昵称
            if (!isNicknameExists(username)) {
                break;
            }

            // 如果存在重复，则将数字部分增加10
            numberPart += 10;
        } while (true);

        return username;
    }

    private boolean isNicknameExists(String username) {
        return userMapper.existsByUsername(username) > 0;
    }


}
